package config

import (
	"sync"
	"time"

	conf "hermestrans/basis/config"
	log "hermestrans/basis/log"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type Config struct {
	InstanceConfig struct {
		Cpu int //实例可使用的cpu个数，默认1
	}
	ServerConfig struct {
		Name               string        //服务名
		ApiPort            int           //restful api端口
		ApiReadTimeout     time.Duration //api的读超时时间(秒级)
		ApiWriteTimeout    time.Duration //api的写超时时间(秒级)
		EtcdEndpoints      []string      //etcd集群信息
		EtcdDialTimeout    time.Duration //etcd链接超时设置
		WebRoot            string
		HTMLFiles          string //前端路径
		HTMLGlob           string
		StaticRelativePath string
		StaticRoot         string
		TargetUrl          string //作为Proxy转发到下游TargetUrl
		RunMode            string //运行模式，debug或者release
	}

	MongoConfig struct {
		MongodbUri               string        //mongo uri
		MongodbName              string        //数据库名
		MongodbConnectionTimeout time.Duration //mongo的连接超时时间
		MaxPoolSize              uint64
	}
	MysqlConfig struct {
		Mysql           mysql.Config
		Gorm            gorm.Config
		MaxIdleConns    int
		MaxOpenConns    int
		ConnMaxIdleTime time.Duration
	}
	RedisConfig struct {
		Addr     string
		Db       int
		Password string
	}
	KfkConfig struct {
		Brokers  []string
		Topic    string
		User     string
		Passwd   string
		Enqueued int
		Timeout  int
		Errs     int
	}

	log.LogConfig
}

var (
	//单例
	confInstance *Config
	confOnce     sync.Once
)

func GetInstanceConf() *Config {
	return confInstance
}

// InitConf 实例化master配置
func InitConf(configFile string) *Config {
	//实例化
	var (
		defaultConfigBytes []byte
		envPrefix          string
	)

	// 赋值单例,由每个服务单独控制
	confOnce.Do(func() {
		confInstance = &Config{}
		conf.LoadConfig(confInstance, defaultConfigBytes, configFile, envPrefix)
	})

	return confInstance
}
